#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
#include <iostream>
#define SIZE 1024
using namespace std;
void Write(int wfd)
{
    //写入内容
    char buffer[SIZE]={0};//缓冲区
    int number =0;//记录写入次数
    const char*message="hello linux!! i am child!!";
    while (true)
    {
        //子不停写
        snprintf(buffer,sizeof(buffer),"%s - pid:%d -%d\n",message,getpid(),number++);
        write(wfd,buffer,strlen(buffer));
         sleep(2);//每隔两秒写
    }
    
}
void Read(int rfd)
{
    char buffer[SIZE]={0};//缓冲区
    while(true)
    {

   ssize_t redcount= read(rfd,buffer,sizeof(buffer));
   if(redcount){
    buffer[redcount]='\0';
   }
   cout<<buffer<<endl;
    }
}
int main()
{
    int pipefd[2];
    int retpipe=pipe(pipefd);//建立管道
    pid_t id=fork();//创建子进程
    if(id<0)return 1;//创建失败
    else if(id==0)
    {
        //child
        //父读子写，子关闭读
        close(pipefd[0]);
        Write(pipefd[1]);
        exit(0);//子写完退出程序
    }
    else
    //farther
    //父读子写，父关闭写
    close(pipefd[1]);
    Read(pipefd[0]);
    pid_t retpid=(id,NULL,0);
    if(retpid<0)return 3;//等待失败
    return 0;
}